<template>
  <div class="app-container">
    <div>
      <el-button type="primary" plain @click="showChuchaiApplyDialog">出差申请</el-button>
    </div>
    <!-- {{list}} -->
    <div style="padding: 10px" />
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="状态" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sta==0 && scope.row.chexiao==0" type="warning">审核</el-tag>
          <el-tag v-if="scope.row.sta==1 && scope.row.chexiao==0" type="success">通过</el-tag>
          <el-tag v-if="scope.row.sta==2 && scope.row.chexiao==0" type="danger">拒绝</el-tag>
          <el-tag v-if="scope.row.chexiao==1" type="info">撤销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请编号" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag> {{ scope.row.id }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="申请时间" align="center" width="110px">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="出发时间" align="center">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.startDate,"MM-DD") }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.endDate,"MM-DD") }}
        </template>
      </el-table-column>

      <el-table-column label="出差天数" align="center">
        <template slot-scope="scope">
          {{ scope.row.days }}天
        </template>
      </el-table-column>
      <el-table-column label="出发地" align="center">
        <template slot-scope="scope">
          {{ scope.row.chufa }}
        </template>
      </el-table-column>
      <el-table-column label="目的地" align="center">
        <template slot-scope="scope">
          {{ scope.row.destination }}
        </template>
      </el-table-column>

      <el-table-column label="出差事由" align="center">
        <template slot-scope="scope">
          {{ scope.row.reason }}
        </template>
      </el-table-column>
      <el-table-column label="交通方式" align="center">
        <template slot-scope="scope">
          {{ scope.row.jiaotong }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="seeDetail(scope.row.id)">详情 </el-button>
          <el-button v-if="scope.row.sta>0 && scope.row.chexiao == 0" size="mini" type="primary" plain @click="printPdf(scope.row.id)">生成PDF </el-button>
          <el-button v-if="(scope.row.chexiao == 0)" size="mini" type="danger" plain @click="revertApply(scope.$index)">撤回 </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div style="padding: 10px" />
    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageCount"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <el-dialog
      :visible.sync="chuchaiApplyDialog.visible"
      width="40%"
      :close-on-click-modal="false"
      top="5vh"
      center
      :show-close="false"
    >
      <div>
        <el-form ref="form" size="mini" label-position="left" label-width="100px">
          <el-row>
            <!-- 左侧 -->
            <el-col :span="11">
              <div class="title"><i class="el-icon-document" /> 申请单</div>

              <el-form-item label="出差人">
                {{ userInfo.name }}
              </el-form-item>

              <el-form-item label="出差人">
                <el-select v-model="chuchaiApplyDialog.chuchairen" multiple placeholder="请选择" style="width: 100%;" @change="chuchairenChange">
                  <el-option v-for="item in allUsers" :key="item.id" :label="item.name" :value="item.uid" />
                </el-select>
              </el-form-item>

              <el-form-item label="部门">
                {{ userInfo.departmentName }}
              </el-form-item>

              <el-form-item label="开始时间">
                <el-date-picker v-model="chuchaiApplyDialog.startDate" type="date" placeholder="选择日期" style="width: 100%;" @change="dateChange" />
              </el-form-item>

              <el-form-item label="结束时间">
                <el-date-picker v-model="chuchaiApplyDialog.endDate" type="date" placeholder="选择日期" style="width: 100%;" @change="dateChange" />
              </el-form-item>

              <el-form-item label="天数">
                {{ qingjiaDaysStr() }}
              </el-form-item>

              <el-form-item label="出发地">
                <el-input v-model="chuchaiApplyDialog.chufa" />
              </el-form-item>

              <el-form-item label="目的地">
                <el-input v-model="chuchaiApplyDialog.destination" />
              </el-form-item>

              <el-form-item label="举办方是否包">
                <el-checkbox-group v-model="chuchaiApplyDialog.bao" placeholder="请选择" style="width: 100%;">
                  <el-checkbox v-for="(yz, idx) in baoList" :key="idx" :label="yz" />
                </el-checkbox-group>
              </el-form-item>

              <el-form-item label="交通工具">
                <el-select v-model="chuchaiApplyDialog.jiaotong" placeholder="请选择" style="width: 100%;" @change="dateChange">
                  <el-option v-for="(item,idx) in jiaotongList" :key="idx" :label="item" :value="item" />
                </el-select>
              </el-form-item>

              <el-form-item label="出差事由">
                <el-input v-model="chuchaiApplyDialog.reason" type="textarea" :rows="4" placeholder="请输入内容" />
              </el-form-item>

              <el-form-item label="附件">
                <el-upload
                  ref="attaches"
                  :action="uploadconfig.url"
                  :on-success="uploadAttachSuccess"
                  list-type="text"
                >
                  <el-button size="mini" type="primary" plain>点击上传附件</el-button>
                </el-upload>
              </el-form-item>

            </el-col>
            <!-- 右侧 -->
            <el-col :span="11" :offset="2">
              <div class="title"><i class="el-icon-s-check" /> 审核流程</div>
              <div v-for="(item,index) in chuchaiApplyDialog.auditors" :key="index">
                <!-- 箭头：第一个不显示 -->
                <div v-if="index>0" class="step-arrow">
                  <el-row>
                    <el-col :span="8">
                      <div><i class="el-icon-caret-bottom" /></div>
                    </el-col>
                  </el-row>
                </div>
                <!-- 步骤样式 -->
                <div class="step">
                  <el-row>
                    <el-col :span="8">
                      <div class="step-info-left">{{ item.stepName || item.positionName }}</div>
                    </el-col>
                    <el-col :span="16">
                      <div class="step-info-right">{{ item.name }}</div>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-col>
          </el-row>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="chuchaiApplyDialog.visible = false">关 闭</el-button>
        <el-button type="primary" @click="clickApply()">提 交</el-button>
      </span>
    </el-dialog>
    <el-dialog title="" width="60%" :visible.sync="detailDialog.visible" top="5vh">
      <chuchai-detail :id="detailDialog.id" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="(detailDialog.visible = false)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { websock } from '@/websock'
import moment from 'moment'
import ChuchaiDetail from '../../components/details/chuchaiDetail.vue'
import { uploadconfig } from '@/const'
import { Message } from 'element-ui'

export default {
  components: { ChuchaiDetail },
  filters: {
    statusFilter(sta) {
      const statusMap = {
        1: 'info',
        2: 'success',
        3: 'danger'
      }
      return statusMap[sta]
    }
  },
  data() {
    return {
      // 人员列表样式(多选)
      props: {
        multiple: true
      },
      // 人员列表数据
      userList: [],
      allUsers: [],
      list: null,
      listLoading: true,
      pageIndex: 1,
      pageCount: 10,
      dataTotal: 0,
      auditors: [], // 审核人
      lingdao: {}, // 领导
      departmentList: null,
      userInfo: {},
      uploadconfig,
      jiaotongList: ['铁路', '汽车', '飞机', '公务车', '轮船', '包干', '其他'],
      baoList: ['包餐饮', '包交通', '包住宿', '无'],
      // 添加员工
      chuchaiApplyDialog: {
        visible: false,
        chuchairen: [],
        startDate: '',
        endDate: '',
        chufa: '',
        destination: '',
        bao: [],
        jiaotong: '铁路',
        reason: '',
        department: '',
        attaches: [],
        auditors: []
      },
      detailDialog: {
        visible: false,
        id: 0
      }
    }
  },
  async created() {
    this.getList()

    this.allUsers = await websock.getAllUsers()
    console.log('all users', this.allUsers)

    this.userInfo = await websock.getUserInfo()

    // this.chuchaiApplyDialog.chuchairen.push({ uid: this.userInfo.uid, name: this.userInfo.name })

    websock.getDepartList().then((data) => {
      this.departmentList = data
    })

    const res = await websock.getContactList()
    console.log('created', res)
    const userList = []
    for (let i = 0; i !== res.length; i++) {
      userList.push({
        value: i + '',
        label: res[i].name,
        children: []
      })
      for (let j = 0; j !== res[i].userList.length; j++) {
        userList[i].children.push({
          label: res[i].userList[j].name,
          value: JSON.stringify({ uid: res[i].userList[j].uid, name: res[i].userList[j].name, srt: res[i].userList[j].srt })
        })
      }
    }
    this.userList = userList

    this.auditors = await websock.getAuditors({ typ: 1 })
    console.log('auditors', this.auditors)
    // this.chuchaiApplyDialog.auditors = this.auditors.slice()

    this.lingdao = await websock.getLingdao()
    console.log('my lingdao info', this.lingdao)

    this.checkAuditors()
  },
  methods: {
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = 'MM-DD HH:mm') {
      return moment(stamp).format(str)
    },
    dateChange() {
      this.checkAuditors()
    },
    getList() {
      this.listLoading = true
      websock.chuchaiApplyRecordWeb({
        pageIndex: this.pageIndex,
        pageCount: this.pageCount
      }).then(
        (data) => {
          this.listLoading = false
          this.list = data.list
          this.dataTotal = data.count
        }
      )
    },
    onPageSizeChange(val) {
      this.pageCount = val
      this.getList()
    },
    onCurrentPageChange(val) {
      this.pageIndex = val
      this.getList()
    },
    // 显示添加员工界面
    showChuchaiApplyDialog() {
      this.chuchaiApplyDialog.visible = true
      this.chuchaiApplyDialog.chuchairen = [this.userInfo.uid]
      this.chuchaiApplyDialog.startDate = ''
      this.chuchaiApplyDialog.endDate = ''
      this.chuchaiApplyDialog.chufa = ''
      this.chuchaiApplyDialog.destination = ''
      this.chuchaiApplyDialog.bao = []
      this.chuchaiApplyDialog.jiaotong = '铁路交通'
      this.chuchaiApplyDialog.reason = ''
      this.chuchaiApplyDialog.department = ''
      this.chuchaiApplyDialog.attaches = []
      if (this.$refs.attaches) this.$refs.attaches.uploadFiles = []
    },
    addAuditor(info) {
      if (!info.uid) return
      for (let i = 0; i != this.chuchaiApplyDialog.auditors.length; i++) {
        if (this.chuchaiApplyDialog.auditors[i].uid == info.uid) return
      }

      this.chuchaiApplyDialog.auditors.push(info)
    },
    uploadAttachSuccess(res, file) {
      console.log('upload attach success', res, file)
      if (res.code !== 0) {
        return Message({
          message: res.message || 'error',
          type: 'error',
          duration: 3 * 1000
        })
      }
      this.chuchaiApplyDialog.attaches.push({
        name: file.name,
        path: res.data
      })
    },
    async checkAuditors() {
      this.chuchaiApplyDialog.auditors = []

      // 添加出差人的直接领导
      // for (let i = 0; i != this.chuchaiApplyDialog.chuchairen.length; i++) {
      //   const lingdao = await websock.getLingdao({ uid: this.chuchaiApplyDialog.chuchairen[i] })
      //   this.addAuditor({ uid: lingdao.zhijie_lingdao, name: lingdao.zhijie_lingdao_name, positionName: lingdao.zhijie_lingdao_position_name })
      // }

      const defaultAuditors = this.auditors.slice()
      for (let i = 0; i != defaultAuditors.length; i++) {
        if (defaultAuditors[i].sta == '0') {
          this.addAuditor(defaultAuditors[i])
        }
      }

      // 请假天数
      const diffDays = moment(this.chuchaiApplyDialog.endDate).diff(moment(this.chuchaiApplyDialog.startDate), 'day') + 1
      // 是否为科长
      const isKezhang = this.userInfo.uid == this.lingdao.zhijie_lingdao
      // 是否出盐城
      const isFeiji = this.chuchaiApplyDialog.jiaotong == '飞机'
      // 目的地是否是盐城
      const isYancheng = this.chuchaiApplyDialog.destination != '盐城'

      if (diffDays > 2 || (isKezhang && diffDays > 0)) {
        this.addAuditor({ uid: this.lingdao.fenguan_lingdao, name: this.lingdao.fenguan_lingdao_name, positionName: this.lingdao.fenguan_lingdao_position_name })
      }
      if (diffDays > 3 || (isKezhang && diffDays > 0) || isFeiji || isYancheng) {
        this.addAuditor({ uid: this.lingdao.zhuyao_lingdao, name: this.lingdao.zhuyao_lingdao_name, positionName: this.lingdao.zhuyao_lingdao_position_name })
      }
    },
    qingjiaDaysStr() {
      if (this.chuchaiApplyDialog.startDate == '' || this.chuchaiApplyDialog.endDate == '') return ''
      const diffDays = moment(this.chuchaiApplyDialog.endDate).diff(moment(this.chuchaiApplyDialog.startDate), 'day')
      if (diffDays < 0) return ''
      return (diffDays + 1) + ' 天'
    },

    async clickApply() {
      console.log(this.chuchaiApplyDialog)

      if (this.chuchaiApplyDialog.startDate == '') {
        return this.$message.error('请选择开始时间')
      }

      if (this.chuchaiApplyDialog.endDate == '') {
        return this.$message.error('请选择结束时间')
      }

      const diffDays = moment(this.chuchaiApplyDialog.endDate).diff(moment(this.chuchaiApplyDialog.startDate),
        'day')
      if (diffDays < 0) return this.$message.error('结束时间应该大于开始时间')

      if (this.chuchaiApplyDialog.reason == '') {
        return this.$message.error('请输入出差事由')
      }

      if (this.chuchaiApplyDialog.chufa == '') {
        return this.$message.error('请输入出差出发地')
      }

      if (this.chuchaiApplyDialog.destination == '') {
        return this.$message.error('请输入出差目的地')
      }

      if (this.chuchaiApplyDialog.auditors.length == 0) {
        return this.$message.error('请选择审核人')
      }

      // 出差人
      const chuchairen = []
      for (let i = 0; i != this.chuchaiApplyDialog.chuchairen.length; i++) {
        const uid = this.chuchaiApplyDialog.chuchairen[i]
        for (let j = 0; j != this.allUsers; j++) {
          if (this.allUsers[j].uid == uid) {
            chuchairen.push({ uid, name: this.allUsers[j].name })
            break
          }
        }
      }

      const auditors = []
      for (let i = 0; i != this.chuchaiApplyDialog.auditors.length; i++) {
        auditors.push({ uid: this.chuchaiApplyDialog.auditors[i].uid, stepName: this.chuchaiApplyDialog.auditors[i].stepName || this.chuchaiApplyDialog.auditors[i].positionName })
      }

      try {
        await websock.chuchaiApply({
          chuchairen,
          startDate: this.chuchaiApplyDialog.startDate,
          endDate: this.chuchaiApplyDialog.endDate,
          reason: this.chuchaiApplyDialog.reason,
          days: diffDays + 1,
          chufa: this.chuchaiApplyDialog.chufa,
          destination: this.chuchaiApplyDialog.destination,
          bao: this.chuchaiApplyDialog.bao,
          jiaotong: this.chuchaiApplyDialog.jiaotong,
          department: this.userInfo.departmentName,
          attaches: this.chuchaiApplyDialog.attaches,
          auditors
        })
        this.$message.success('提交成功，等待审批')

        this.getList()

        this.chuchaiApplyDialog.visible = false
      } catch (err) {
        this.$message.error(err.message || 'error')
      }
    },
    async revertApply(idx) {
      try {
        await websock.revertChuchaiApply({
          id: this.list[idx].id
        })
        this.list[idx].sta = 4
        this.getList()
      } catch (err) {
        console.error(err)
        this.$message.error({
          title: err.message || 'error'
        })
      }
    },
    seeDetail(id) {
      this.detailDialog.visible = true
      this.detailDialog.id = id
    },
    printPdf(id) {
      websock.printPdf({ typ: 1, id }).then(res => {
        console.log('print pdf', res)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = res
        a.target = '_blank'
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(a.href)
        document.body.removeChild(a)
      })
    },
    async chuchairenChange(e) {
      console.log('chuchairen changed')
      // console.log(e)
      console.log(this.chuchaiApplyDialog.chuchairen)
      if (this.chuchaiApplyDialog.chuchairen.indexOf(this.userInfo.uid) == -1) {
        this.chuchaiApplyDialog.chuchairen = [this.userInfo.uid, ...this.chuchaiApplyDialog.chuchairen]
      }

      this.chuchaiApplyDialog.chuchairen.sort((a, b) => {
        let asrt = 0
        let bsrt = 0
        for (let i = 0; i != this.allUsers.length; i++) {
          if (this.allUsers[i].uid == a) asrt = i
          if (this.allUsers[i].uid == b) bsrt = i
        }
        if (asrt == bsrt) return 0
        return asrt > bsrt ? 1 : -1
      })

      this.checkAuditors()
    }
  }
}
</script>

<style>
@import url("../../styles/form.css");
</style>
